package concurrency;

/**
 * 加入一个线程
 *
 * 2018年 09月 24日 星期一
 * @author fireway
 */
class Sleeper extends Thread {
    private int mDuration;

    public Sleeper(String name, int sleepTime) {
        super(name);
        mDuration = sleepTime;
        start();
    }

    @Override
    public void run() {
        try {
            sleep(mDuration);
        } catch (InterruptedException e) {
            System.out.println(getName() + " was interrupted, isInterrupted? " + isInterrupted());
            return;
        }
        System.out.println(getName() + " has awakened");
    }
}

class Joiner extends Thread {
    private Sleeper mSleeper;

    public Joiner(String name, Sleeper sleeper) {
        super(name);
        mSleeper = sleeper;
        start();
    }

    @Override
    public void run() {
        try {
            mSleeper.join();
        } catch (InterruptedException e) {
            System.out.println(getName() + " was interrupted, isInterrupted? " + isInterrupted());
        }
        System.out.println(getName() + " join completed");
    }
}

public class Joining {
    public static void main(String[] args) {
        Sleeper sleepy = new Sleeper("sleepy", 5000);
        Sleeper grumpy = new Sleeper("grumpy", 5000);

        Joiner dopey = new Joiner("dopey", sleepy);
        Joiner doc = new Joiner("doc", grumpy);

        grumpy.interrupt();
    }
}
